package com.lin.zoo.view;

import com.lin.zoo.controller.ActivityController;
import com.lin.zoo.util.DataBase;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;

public class ActivityFeederPage {
    private JFrame frame=new JFrame("活动管理系统");//新窗口
    private JButton addButton, delButton,inquireButton,setIntroduceButton,setParkIdButton,setStartButton,setEndTime;//添加活动，删除活动，查询活动，以及更改各项数据的按钮
    private JTable jTable;//使用表格展示数据
    private DefaultTableModel mol;
    private JScrollPane scrollPane;//为表格添加滚轮
    private JPanel panel;//安放按钮
    private JTextField jText=new JTextField("请在此输入修改的数据");//用于用户输入数据
    private Vector<String> rowVector;//存放列数据
    private Vector<Vector<String>> dataVector;//存放数据
    private Connection con;
    private PreparedStatement state;
    private ResultSet rs;

    private ActivityController activityController=new ActivityController();//连接活动窗口

    public JButton getAddButton() {
        return addButton;
    }

    public void setAddButton(JButton addButton) {
        this.addButton = addButton;
    }

    public JButton getDelButton() {
        return delButton;
    }

    public void setDelButton(JButton delButton) {
        this.delButton = delButton;
    }

    public JButton getInquireButton() {
        return inquireButton;
    }

    public void setInquireButton(JButton inquireButton) {
        this.inquireButton = inquireButton;
    }

    public JButton getSetIntroduceButton() {
        return setIntroduceButton;
    }

    public void setSetIntroduceButton(JButton setIntroduceButton) {
        this.setIntroduceButton = setIntroduceButton;
    }

    public JButton getSetParkIdButton() {
        return setParkIdButton;
    }

    public void setSetParkIdButton(JButton setParkIdButton) {
        this.setParkIdButton = setParkIdButton;
    }

    public JButton getSetStartButton() {
        return setStartButton;
    }

    public void setSetStartButton(JButton setStartButton) {
        this.setStartButton = setStartButton;
    }

    public JButton getSetEndTime() {
        return setEndTime;
    }

    public void setSetEndTime(JButton setEndTime) {
        this.setEndTime = setEndTime;
    }

    public ActivityController getActivityController() {
        return activityController;
    }

    public void setActivityController(ActivityController activityController) {
        this.activityController = activityController;
    }

    public void createAndShowGUI() throws SQLException{
        setActivityController(new ActivityController());
        frame.setVisible(true);
        frame.setSize(1000,400);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // 显示窗口
        frame.setResizable(false);
        //固定窗口大小不被修改
        frame.setLocationRelativeTo(null);
        //窗口处于中央
        rowVector= new Vector<>();
        rowVector.add("id");
        rowVector.add("活动介绍");
        rowVector.add("所在园区");
        rowVector.add("开始时间");
        rowVector.add("结束时间");//列名称
        mol = new DefaultTableModel();
        try{
            con =DataBase.getCon();
            state = con.prepareStatement("select * from activity");
            rs=state.executeQuery();
        }catch (ClassNotFoundException e) {
            System.out.println("数据读取错误"+this.getClass().getName());
        }//直接在view中调用了数据库，展示所有的活动
        setData(rs);//将读取的数据存放在dataVector中
        DataBase.close(state, con);
        jTable=new JTable(mol);
        jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        scrollPane=new JScrollPane(jTable);//为表格添加滚轮

        TableColumn introductionColumn = jTable.getColumnModel().getColumn(1);
        introductionColumn.setPreferredWidth(800);//修改介绍一列的行距

        TableColumn idColumn = jTable.getColumnModel().getColumn(0);
        idColumn.setPreferredWidth(20);//修改id一行的行距

        jTable.setRowHeight(50);
        frame.add(scrollPane,BorderLayout.CENTER);//展示表格
        init();

        frame.add(panel,BorderLayout.SOUTH);//将按钮放置在底部
        //删除按钮
        getDelButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();//选中行
                seletedRow=jTable.convertRowIndexToModel(seletedRow);
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                if(seletedRow !=-1){
                    mol.removeRow(seletedRow);//从表格中移除数据
                }
                getActivityController().delactivity(id);//删除选中活动
                JOptionPane.showMessageDialog(null, "删除成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //添加活动按钮
        getAddButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Vector<String> row= new Vector<>();
                try {
                    con = DataBase.getCon();
                    state = con.prepareStatement("insert into activity (introduce,parkid,starttime,endtime) values(?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
                    state.setObject(1," ");
                    state.setObject(2,0);
                    state.setObject(3," ");
                    state.setObject(4," ");
                    state.executeUpdate();//完成新的活动，空信息表的创建
                    try (ResultSet rs = state.getGeneratedKeys()) {
                        if (rs.next()) {
                            String id = rs.getString(1);
                            row.add(id);
                            row.add(" ");
                            row.add("0");
                            row.add(" ");
                            row.add(" ");//将新创建的信息反馈到界面以便进一步地修改
                            mol.addRow(row);
                        }
                    }
                    DataBase.close(state,con);
                }
                catch (SQLException | ClassNotFoundException ex) {
                    System.out.println("数据添加错误"+this.getClass().getName());
                }
                JOptionPane.showMessageDialog(null, "添加成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });

        //修改活动介绍
        getSetIntroduceButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                String introduce=jText.getText();//读取用户输入的数据
                jTable.setValueAt(introduce,seletedRow,1);//反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getActivityController().setIntroduce(id,introduce);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //设置所在园区
        getSetParkIdButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                String parkId=jText.getText();//读取用户输入的数据
                jTable.setValueAt(parkId,seletedRow,2);//反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getActivityController().setPark(id,parkId);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //设置开始时间
        getSetStartButton().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                String time=jText.getText();//读取用户输入的数据
                jTable.setValueAt(time,seletedRow,3);//反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getActivityController().setStart(id,time);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
        //设置结束时间
        getSetEndTime().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int seletedRow=jTable.getSelectedRow();
                seletedRow=jTable.convertRowIndexToModel(seletedRow);//记录选中行
                Object id=jTable.getValueAt(seletedRow+0,0);//读取选中行的id
                String time=jText.getText();//读取用户输入的数据
                jTable.setValueAt(time,seletedRow,4);//反馈到界面
                jTable.repaint();
                jText.setText("请在此输入需要修改的数据");
                getActivityController().setEnd(id,time);
                JOptionPane.showMessageDialog(null, "修改成功", null, JOptionPane.PLAIN_MESSAGE);
            }
        });
    }

    public void init(){
        panel=new JPanel();
        addButton =new JButton("添加活动");
        delButton =new JButton("删除活动");
        setIntroduceButton=new JButton("设置活动介绍");
        setParkIdButton=new JButton("设置所在园区");
        setStartButton=new JButton("设置开始时间");
        setEndTime=new JButton("设置结束时间");//设置按钮的文本文字

        panel.setLayout(new GridLayout(2,1));
        panel.add(addButton);
        panel.add(delButton);
        panel.add(setIntroduceButton);
        panel.add(setParkIdButton);
        panel.add(setStartButton);
        panel.add(setEndTime);
        panel.add(jText);//添加按钮承载的panel，分布为两行
    }
    //将读取到的数据放置到dataVector
    public void setData(ResultSet rs) throws SQLException{
        dataVector = new Vector<>();
        while(rs.next()) {
            Vector<String> vector = new Vector<>();
            for (int i = 1; i <= 5; i++)//5代表列数
                vector.add(rs.getString(i));//添加数据库数据到vector
            dataVector.add(vector);//添加vector数据到dataVector
        }
        mol.setDataVector(dataVector,rowVector);//最后将数据输入至mol
    }
}
